/**
 *
 * @description:
 * @author: junyong.hong
 * @createTime: 2018/10/12
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
// schema 文档：描述数据字段
// model  数据模型
// entity 一条数据的实例
const mongoose = require('mongoose')
const Schema = mongoose.Schema

const TokenSchema = new Schema({
    name: String,       // accessToken
    token: String,
    expires_in: Number, // 失效时间
    meta: {
        createdAt: {
            type: Date,
            default: Date.now()
        },
        updatedAt: {
            type: Date,
            default: Date.now()
        }
    }
})

TokenSchema.pre('save', function (next) {
    // 如果是新增的
    if (this.isNew) {
        this.meta.createdAt = this.meta.updatedAt = Date.now()
    } else {
        this.meta.updatedAt = Date.now()
    }

    next()
})

// 静态方法
TokenSchema.statics = {
    /**
     * 获取token
     * @returns {Promise.<*>}
     */
    async getAccessToken () {
        // 先查token
        const token = await this.findOne({
            name: 'access_token'
        })

        if (token && token.token) {
            token.access_token = token.token
        }

        return token
    },
    /**
     * 保存token
     * @param data
     * @returns {Promise.<*>}
     */
    async saveAccessToken (data) {
        // 先查token
        let token = await this.findOne({
            name: 'access_token'
        })

        if (token) {
            token.token = data.access_token
            token.expires_in = data.expires_in
        } else {
            token = new Token({
                name: 'access_token',
                token: data.access_token,
                expires_in: data.expires_in
            })
        }

        await token.save()

        return data
    }
}

const Token = mongoose.model('Token', TokenSchema)
